package filedb

import (
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/datax/convertx"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"github.com/syndtr/goleveldb/leveldb"
)

var ldb *leveldb.DB

func Init(file string) (err error) {
	db, err := leveldb.OpenFile(file, nil)
	if err != nil {
		err = errorx.Wrap(err, "open file db", datax.M{"file": file})
		return
	}
	ldb = db
	return
}

func Put(key string, val interface{}) (err error) {
	if ldb == nil {
		return errorx.New("file db not init")
	}
	valstr := convertx.AnyToString(val)
	putErr := ldb.Put([]byte(key), []byte(valstr), nil)
	if putErr != nil {
		err = errorx.Wrap(putErr, "put file db", datax.M{"key": key})
		return
	}
	return
}

func Get(key string) (val string, err error) {
	if ldb == nil {
		return "", errorx.New("file db not init")
	}
	ival, getErr := ldb.Get([]byte(key), nil)
	if getErr != nil {
		if getErr.Error() == "leveldb: not found" {
			return
		}
		err = errorx.Wrap(getErr, "get file db", datax.M{"key": key})
		return
	}
	return string(ival), nil
}
